package kr.haggenna.member.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import kr.haggenna.item.dao.ItemDao;
import kr.haggenna.item.domain.Item;
import kr.haggenna.member.dao.MemberDao;
import kr.haggenna.member.domain.MemberCommand;
import kr.haggenna.member.util.CipherTemplate;
import kr.haggenna.member.validator.UpdateValidator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class UpdateController {
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private ItemDao itemDao;
	
	@Resource(name="cipherAES")
	private CipherTemplate cipherAES;
	
	@RequestMapping(value="/update.do",method=RequestMethod.POST)
	public ModelAndView submit(@ModelAttribute MemberCommand memberCommand, BindingResult result){
		
		ModelAndView mav = new ModelAndView();
		new UpdateValidator().validate(memberCommand,result);
		
		if(result.hasErrors()){
			
			List<Item> itemList = new ArrayList<Item>();
			
			List<Item> bakeryList = itemDao.getBakeryList();
			List<Item> baverageList = itemDao.getBeverageList();
			List<Item> coffeeList = itemDao.getCoffeeList();
			
			for(Item item : coffeeList){
				itemList.add(item);
			}
			for(Item item : baverageList){
				itemList.add(item);
			}
			for(Item item : bakeryList){
				itemList.add(item);
			}
			
			mav.setViewName("updateForm");
			mav.addObject("memberCommand", memberCommand);
			mav.addObject("itemList", itemList);
			
			return mav;
		}
		
		memberCommand.setPasswd(cipherAES.encrypt(memberCommand.getPasswd()));
		memberDao.updateMember(memberCommand);
		
		mav.setViewName("updatePro");
		return mav;
		
	}
	
}
